<template>
  <div class="addFreight">
    <h2 class="editPage">{{ id ? "修改" : "新增" }}</h2>
    <a-card>
      <a-form :form="form">
        <a-form-item
          label="模板名称"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-input
            placeholder="请输入模板名称"
            @change="templateNameChange"
            v-decorator="[
              'templateName',
              {
                rules: [{ required: true, message: '请输入模板名称' }],
              },
            ]"
          ></a-input>
        </a-form-item>

        <a-form-item
          label="规格名称"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <div>
            <template v-for="(tag, index) in specificationValues">
              <a-tooltip v-if="tag.name.length > 20" :key="tag.name" :title="tag.name">
                <a-tag
                  :key="tag.name"
                  :closable="index !== 0"
                  @close="() => handleClose(tag.name)"
                >
                  {{ `${tag.name.slice(0, 20)}...` }}
                </a-tag>
              </a-tooltip>
              <a-tag
                v-else
                :key="tag.name"
                :closable="index !== 0"
                @close="() => handleClose(tag.name)"
              >
                {{ tag.name }}
              </a-tag>
            </template>
            <a-input
              v-if="inputVisible"
              ref="input"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              :value="inputValue"
              @change="handleInputChange"
              @blur="handleInputConfirm"
              @keyup.enter="handleInputConfirm"
            />
            <a-tag
              v-else
              style="background: #fff; borderstyle: dashed"
              @click="showInput"
            >
              <a-icon type="plus" /> +规格
            </a-tag>
          </div>
          <!-- <a-input
            placeholder="请输入规格名称"
            @change="templateNameChange"
            v-decorator="[
              'templateName',
              {
                rules: [{ required: true, message: '请输入规格名称' }],
              },
            ]"
          ></a-input> -->
        </a-form-item>
        <a-form-item
          v-for="(item, index_) in specificationValues"
          :key="index_"
          :label="item.name"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <div>
            <template v-for="(tag, index) in item.value_">
              <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
                <a-tag
                  :key="tag"
                  :closable="index !== 0"
                  @close="() => handleClose2(tag, index_)"
                >
                  {{ `${tag.slice(0, 20)}...` }}
                </a-tag>
              </a-tooltip>
              <a-tag
                v-else
                :key="tag"
                :closable="index !== 0"
                @close="() => handleClose2(tag, index_)"
              >
                {{ tag }}
              </a-tag>
            </template>
            <a-input
              v-if="inputVisible2[index_]"
              type="text"
              size="small"
              :style="{ width: '78px' }"
              :value="inputValue2"
              @change="handleInputChange2"
              @blur="handleInputConfirm2(index_)"
              @keyup.enter="handleInputConfirm2(index_)"
            />
            <a-tag
              v-else
              style="background: #fff; borderstyle: dashed"
              @click="showInput2(index_)"
            >
              <a-icon type="plus" /> +规格值
            </a-tag>
          </div>
        </a-form-item>

        <div>
          <a-button
            type="primary"
            class="marginBtn"
            @click="AddFreightAction"
            >确定</a-button
          >
          <a-button @click="$router.go(-1)" class="marginBtn">返回</a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import * as API from "../../api/freight";
import { mapState } from "vuex";

export default {
  name: "Freight",
  data() {
    return {
      loading: false,
      form: this.$form.createForm(this),
      id: null,
      loading: false,
      postUserData: {},
      specificationValues: [{ name: "大小", value_: [] }],
      inputVisible: false,
      inputValue: "",
      // tags2: [''],
      inputVisible2:[false],
      inputValue2: "",
    };
  },
  mounted() {
    this.getbrandInfo();
  },
  created() {
    this.id = this.$route.query.id || null;
  },

  activated() {},
  methods: {
    setFields(submitData) {
      submitData.specificationValues.forEach(item=>{
        item.value_ = item.value.split(',')
      })
        this.specificationValues = submitData.specificationValues
      this.form.setFieldsValue({
        templateName: submitData.templateName,
        // keywords: submitData.keywords,
        // logoPath: submitData.logoPath,
        // introduction: submitData.introduction,
      });
    },
    //详情
    getbrandInfo() {
      if (this.id) {
        API.getFreightDetail(this.id).then((res) => {
          this.postUserData = res.data;
          this.setFields(res.data);
        });
      }
    },

    onChange(e) {
      this.postUserData.introduction = e.target.value;
    },
    roleChange(value) {
      this.postUserData.FreightType = value;
      // console.log(value, 5555);
    },

    editorActon(editorContent) {
      this.postUserData.remark = editorContent;
    },

    AddFreightAction() {
      this.form.validateFields((err) => {
        if (!err) {
          this.specificationValues.forEach(item => {
            console.log(item.value_, '3333333333333')
            item.value = item.value_?item.value_.join(','):''
          })
          this.postUserData.specificationValues = this.specificationValues
          this.id ? this.edit() : this.add();
          //  this.add();
        }
      });
    },
    //新增
    add() {
      console.log(this.postUserData);
      this.loading = true;
      API.addFreight(this.postUserData)
        .then((res) => {
          if (res.code === 200) {
            // this.$message.destroy();
            this.$message.success("添加成功");
            this.$router.go(-1);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //修改
    edit() {
      this.loading = true;
      API.editFreight(this.id, this.postUserData)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("修改成功");
            this.$router.go(-1);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    filterOption(input, option) {
      console.log(input, option);
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    //表单参数
    templateNameChange(e) {
      // console.log(e.target.value);
      this.postUserData.templateName = e.target.value;
    },
    // keywordsChage(e) {
    //   this.postUserData.keywords = e.target.value;
    // },
    // 规格
    handleClose(removedTag) {
      const specificationValues = this.specificationValues.filter((tag) => tag.name !== removedTag);
      console.log(specificationValues);
      this.specificationValues = specificationValues;
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },

    handleInputChange(e) {
      this.inputValue = e.target.value;
    },

    handleInputConfirm() {
      const inputValue = this.inputValue;
      let specificationValues = this.specificationValues;
      let name = specificationValues.map(item => item.name)
      if (inputValue && name.indexOf(inputValue) === -1) {
        let obj = { name: inputValue, value_: [] }
        // specificationValues = [...specificationValues, inputValue];
        specificationValues.push(obj)
      }
      console.log(specificationValues);
      Object.assign(this, {
        specificationValues,
        inputVisible: false,
        inputValue: "",
      });
    },

    // 规格值
    handleClose2(removedTag, index) {
      const specificationValues = this.specificationValues[index].value_.filter((tag) => tag !== removedTag);
      console.log(specificationValues);
      this.specificationValues[index].value_ = specificationValues;
    },

    showInput2(index) {
      // this.inputVisible2[index] = true;
      this.$set(this.inputVisible2, index, true)
      // console.log(this.inputVisible2, 44444444444)
      // this.$nextTick(function () {
      //   let val = 'input2'+index
      //   this.$refs[val].focus();
      // });
    },

    handleInputChange2(e) {
      this.inputValue2 = e.target.value;
    },

    handleInputConfirm2(index) {
      const inputValue2 = this.inputValue2;
      let specificationValues = this.specificationValues[index];
      if (inputValue2 && specificationValues.value_.indexOf(inputValue2) === -1) {
        specificationValues.value_ = [...specificationValues.value_, inputValue2];
      }
      console.log(specificationValues.value_);
      this.$set(this.inputVisible2, index, false)
      this.$set(this.specificationValues, index, specificationValues)
      this.inputValue2 = ''
      // Object.assign(this, {
        // specificationValues,
        // inputVisible2: false,
        // inputValue2: "",
      // });
    },
  },
};
</script>
